﻿@page "/htmltoexcel"

@using RazorEngine
@using RazorEngine.Templating
@using RazorEngine.Configuration;
@using RazorEngine.Text;

@inject IJSRuntime JSRuntime

<Button OnClick="OnClick" Text="试试"></Button>

<script type="text/javascript">
    window.downloadFileFromStream = async (fileName, contentStreamReference) => {
        const arrayBuffer = await contentStreamReference.arrayBuffer();
        const blob = new Blob([arrayBuffer]);
        const url = URL.createObjectURL(blob);
        const anchorElement = document.createElement('a');
        anchorElement.href = url;
        anchorElement.download = fileName ?? '';
        anchorElement.click();
        anchorElement.remove();
        URL.revokeObjectURL(url);
    }
</script>


@code {
    async Task OnClick()
    {
        // var config = new TemplateServiceConfiguration();
        // config.Language = Language.CSharp; // VB.NET as template language.
        // config.EncodedStringFactory = new RawStringFactory(); // Raw string encoding.
        // config.EncodedStringFactory = new HtmlEncodedStringFactory(); // Html encoding.
         // string template = "Hello @Model.Name, welcome to RazorEngine!";
        // var result = Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });
        // config.ReferenceResolver = new MyIReferenceResolver();
        // var service = RazorEngineService.Create(config);

        List<Student> students = new()
                {
                    new Student(){  Id=1,Name="Tom",Age=18,Address="浙江省宁波市ds鄞州区"},
                    new Student(){  Id=2,Name="流川枫",Age=18,Address="浙江省宁波市海曙区"},
                    new Student(){  Id=3,Name="樱木花道",Age=18,Address="浙江省宁波市江东区"},
                    new Student(){  Id=4,Name="Lucy",Age=18,Address="浙江省宁波市北仑区"},
                };

        string path = Path.Combine("Pages/Templates/Index.cshtml");

        var template = File.ReadAllText(path);

        //var result = service.RunCompile(template, "templateKey2", typeof(List<Student>), students);

        var result = Engine.Razor.RunCompile(template, "templateKey2",typeof(List<Student>), students);

        byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(result);

        var fileStream = new MemoryStream(fileBytes);

        var fileName = "aaa.xls";

        using var streamRef = new DotNetStreamReference(stream: fileStream);

        //https://learn.microsoft.com/zh-cn/aspnet/core/blazor/file-downloads?view=aspnetcore-7.0#download-from-a-stream

        await JSRuntime.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
    }

    
}
